package cn.modfun.web.core.config;

import cn.hutool.setting.Setting;
import com.jfinal.config.*;
import com.jfinal.json.MixedJsonFactory;
import com.jfinal.log.Log;
import com.jfinal.plugin.log4j2.Log4j2Plugin;
import com.jfinal.plugin.mysql.MysqlDataSourcePlugin;
import com.jfinal.plugin.router.RouterPlugin;
import com.jfinal.template.Engine;

public class DefaultConfig extends JFinalConfig {

    /**
     * 先加载开发环境配置，再追加生产环境的少量配置覆盖掉开发环境配置
     */
    private static Setting setting = null;

    static{
        try {
            setting = new Setting("config/jfinal.txt");
        } catch (Exception e) {
            Log.getLog(DefaultConfig.class).error("未找到 {} 配置文件，使用默认配置","config/jfinal.txt");
            setting = new Setting();
            setting.put("common","devMode","false");
            setting.put("common","engine.devMode","false");
        }
    }
    /**
     * 定义常量
     * @param constants
     */
    public void configConstant(Constants constants) {
        /**
         * 设置日志工厂为log4j2
         */
        constants.setLogFactory(new Log4j2Plugin().getLogFactory());
        /**
         * 设置开发模式
         */
        constants.setDevMode(setting.getBool("devMode", "common",false));
        /**
         * 设置JFinalJson 与 FastJson 混用工厂
         */
        constants.setJsonFactory(MixedJsonFactory.me());
        /**
         * 支持 Controller、Interceptor 之中使用 @Inject 注入业务层，并且自动实现 AOP
         */
        constants.setInjectDependency(true);
    }

    /**
     * 配置路由
     * @param routes
     */
    public void configRoute(Routes routes) {
        /**
         * 加载路由
         */
        new RouterPlugin(routes).start();
    }

    public void configEngine(Engine engine) {
        /**
         * 设置模式
         */
        engine.setDevMode(setting.getBool("engine.devMode","common", false));
    }

    public void configPlugin(Plugins plugins) {
        /**
         * 初始化其他插件
         */
        /* mysql 数据库插件 */
        new MysqlDataSourcePlugin().start();
    }

    public void configInterceptor(Interceptors interceptors) {

    }

    public void configHandler(Handlers handlers) {

    }
}
